package com.ms.p2p.plugin.storage;

import com.ms.common.bean.FileInfo;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ms.common.Constants.UPLOAD_PATH_PREFIX;

@Component(value="ftpPlugin")
public class FtpPlugin extends StoragePlugin {
	
	public void upload(String path, File file, String contentType) {
		JSONObject configs = getConfig();
		String host = (String)configs.get("host");
		int port = Integer.parseInt((String)configs.get("port"));
		String username = (String)configs.get("username");
		String password = (String)configs.get("password");
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
//		conf.setServerLanguageCode("zh");


		FTPClient ftpclient = new FTPClient();
		ftpclient.configure(conf);
//		ftpclient.setBufferSize(1024);
//		ftpclient.setControlEncoding("GBK");
		ftpclient.setBufferSize(1024);
		ftpclient.setControlEncoding("UTF-8");

		try {
			int reply;
			ftpclient.connect(host, port);// 连接FTP服务器
			ftpclient.login(username, password);// 登录
			ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpclient.enterLocalPassiveMode();
			reply = ftpclient.getReplyCode();
			if (FTPReply.isPositiveCompletion(reply)) {
				String path_prefix = UPLOAD_PATH_PREFIX + StringUtils.substringBeforeLast(path, "/");
				String fileName = StringUtils.substringAfterLast(path, "/");
				
				if (!ftpclient.changeWorkingDirectory(path_prefix)) {
					String as[] = StringUtils.split(path_prefix, "/");
					String s5 = "/";
					ftpclient.changeWorkingDirectory(s5);
					for (int i = 0, len = as.length; i < len; i++) {
						String s6 = as[i];
						s5 = new StringBuilder(s5).append(s6).append("/").toString();
						if (!ftpclient.changeWorkingDirectory(s5)) {
							ftpclient.makeDirectory(s6);
							ftpclient.changeWorkingDirectory(s5);
						}
					}
				}
				ftpclient.storeFile(fileName, fileInputStream);
				ftpclient.logout();
			}
			IOUtils.closeQuietly(fileInputStream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpclient.isConnected()) {
				try {
					ftpclient.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
	}

	@Override
	public String getUrl(String path) {
		JSONObject configs = getConfig();
		if (configs != null) {
			String url = configs.getString("url");
			return new StringBuilder(url).append(path).toString();
		} 
		return null;
	}
	
	@Override
	public List<FileInfo> browser(String path) {
		JSONObject configs = getConfig();
		if (configs == null) {
			return null;
		}
		String browsetFolder = UPLOAD_PATH_PREFIX + path;
		
		String host = configs.getString("host");
		Integer port = configs.getInt("port");
		String username = configs.getString("username");
		String password = configs.getString("password");
		String url = configs.getString("url");


		List<FileInfo> arraylist = new ArrayList<FileInfo>();
		FTPClient ftpclient = new FTPClient();
		FTPClientConfig config=new FTPClientConfig(FTPClientConfig.SYST_UNIX);
		ftpclient.configure(config);
		try {
			ftpclient.connect(host, port);// 连接FTP服务器
			ftpclient.login(username, password);// 登录
			ftpclient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
			ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
			ftpclient.enterLocalPassiveMode();
			if (FTPReply.isPositiveCompletion(ftpclient.getReplyCode()) && 
					ftpclient.changeWorkingDirectory(browsetFolder)) {
				FTPFile[] aftpfile = ftpclient.listFiles();
				for (int i = 0; i < aftpfile.length; i++) {
					FTPFile ftpfile = aftpfile[i];
					FileInfo fileinfo = new FileInfo();
					fileinfo.setName(ftpfile.getName());
					fileinfo.setStorePath(this.getId() + "://" + path + ftpfile.getName());
					fileinfo.setUrl(new StringBuilder(url).append(path).append(ftpfile.getName()).toString());
					fileinfo.setIsDirectory(ftpfile.isDirectory());
					fileinfo.setSize(ftpfile.getSize());
					fileinfo.setLastModified(ftpfile.getTimestamp().getTime());
					arraylist.add(fileinfo);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftpclient.isConnected()){
				try {
					ftpclient.disconnect();
				} catch (IOException ioexception1) { 
					
				}
			}
		}
		return arraylist;
	}


	public String getType() {
		return "storage";
	}
	
	public String getName(){
		return "FTP上传";
	}

	public String getVersion(){
		return "1.0";
	}

	public String getAuthor(){
		return "yangrongchang";
	}

	public void perform(Object... params) {
		
	}


	public void register() {
		
	}

}
